const express = require('express');
const router = express.Router();
const svgCaptcha = require('svg-captcha');
const ManagerModel = require('../../model/managerModel');
const md5 = require('md5');

router.get('/', async (req, res)=>{

  // let result = new ManagerModel({
  //   username: 'admin',
  //   password: md5('123456')
  // })

  // await result.save();

  res.render('admin/login/login.html');
});

//验证验证码
router.post('/doLogin', async (req, res)=>{
  let username = req.body.username;
  let password = req.body.password;
  let verify = req.body.verify;

  // 1.判断验证码是否正确
  if(verify.toLocaleLowerCase() != req.session.captcha.toLocaleLowerCase()){
    // res.send('验证码错误');
    res.render('admin/public/error.html', {
      'redirectUrl': `/${req.app.locals.adminPath}/login`,
      'message': '验证码错误'
    });
    return;
  }

  // 2.判断用户名是否合法
  let result = await ManagerModel.find({
    'username': username,
    'password': md5(password)
  });
  console.log(result[0]);
  if(result.length > 0){
    //保存用户信息，用于权限认证
    req.session.userinfo = result[0];

    //验证成功
    res.render('admin/public/success.html', {
      'redirectUrl': `/${req.app.locals.adminPath}`,
      'message': '登录成功'
    });
  }else{
    res.render('admin/public/error.html', {
      'redirectUrl': `/${req.app.locals.adminPath}/login`,
      'message': '用户名或密码错误'
    });
    return;
  }
});

// 验证码图片
router.get('/verify', (req, res)=>{
  var captcha = svgCaptcha.create();
  console.log(captcha.text);
  //这里将验证码存入session
  req.session.captcha = captcha.text;
  res.type('svg');
  res.status(200).send(captcha.data);
});

// 退出登录
router.get('/loginOut', (req, res)=>{
  req.session.userinfo = '';
  res.redirect(`/${req.app.locals.adminPath}/login`);
});

module.exports = router;